using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Caching;
using ASPNETVN.PORTAL.Components.Configuration.Items;
using ASPNETVN.PORTAL.Components.Configuration.Settings;
using ASPNETVN.PORTAL.Components.UI;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;

namespace ASPNETVN.PORTAL.Components.Configuration
{
    public class PortalConfiguration
    {
        public static void UpdateVisitorNumber(Guid portalID)
        {
            const string spName = "[dbo].[p_SYSTEM_Information_UpdateVisitorNumber]";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@PortalID", SqlDbType.UniqueIdentifier, portalID);
            db.ExecuteNonQuery(dbCommand);
        }

        public static int GetVisitorNumber(Guid portalID)
        {
            const string spName = "[dbo].[p_SYSTEM_Information_GetVisitorNumber]";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@PortalID", SqlDbType.UniqueIdentifier, portalID);
            db.AddOutParameter(dbCommand, "@ReturnValue", SqlDbType.Int, 4);
            db.ExecuteNonQuery(dbCommand);
            return (int) dbCommand.Parameters["@ReturnValue"].Value;
        }

        public static void IncreaseOnlineNumber(Guid portalID)
        {
            const string spName = "[dbo].[p_SYSTEM_Information_IncreaseOnlineNumber]";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@PortalID", SqlDbType.UniqueIdentifier, portalID);
            db.ExecuteNonQuery(dbCommand);
        }

        public static void DecreaseOnlineNumber(Guid portalID)
        {
            const string spName = "[dbo].[p_SYSTEM_Information_DecreaseOnlineNumber]";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@PortalID", SqlDbType.UniqueIdentifier, portalID);
            db.ExecuteNonQuery(dbCommand);
        }

        public static int GetOnlineNumber(Guid portalID)
        {
            const string spName = "[dbo].[p_SYSTEM_Information_GetOnlineNumber]";
            SqlDatabase db = (SqlDatabase)DatabaseFactory.CreateDatabase();
            SqlCommand dbCommand = (SqlCommand)db.GetStoredProcCommand(spName);

            db.AddInParameter(dbCommand, "@PortalID", SqlDbType.UniqueIdentifier, portalID);
            db.AddOutParameter(dbCommand, "@ReturnValue", SqlDbType.Int, 4);
            db.ExecuteNonQuery(dbCommand);
            return (int)dbCommand.Parameters["@ReturnValue"].Value;
        }

        public void UpdatePortalInfo(Guid portalID, string portalName, string layoutName, string defaultTheme, bool alwaysShowEditButton, string language, bool allowRegister)
        {
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();
            PortalDataSet.PortalRow globalRow = ds.Portal.FindByID(portalID);
            globalRow.ID = portalID;
            globalRow.Title = portalName;
            globalRow.Layout = layoutName;
            globalRow.DefaultTheme = defaultTheme;
            globalRow.AlwaysShowEditButton = alwaysShowEditButton;
            globalRow.Language = language;
            globalRow.AllowRegister = allowRegister;
            
            // Apply all theme of tabs in portal.
            foreach (PortalDataSet.TabRow tab in ds.Tab.Rows)
            {
                tab.ThemeName = globalRow.DefaultTheme;                
            }
            // Save settings.
            SaveSiteSettings();
        }

        //
        // TABS
        //

        public Guid AddTab(Tab tab)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Create a new TabRow from the Tab table
            PortalDataSet.TabRow newRow = ds.Tab.NewTabRow();

            // Set the properties on the new row
            newRow.ID = Guid.NewGuid();
            newRow.ParentID = tab.ParentID;
            newRow.PortalID = tab.PortalID;
            newRow.Name = tab.Name;
            newRow.ThemeName = tab.ThemeName;
            newRow.SortOrder = tab.SortOrder;
            newRow.ShowLeftPane = tab.ShowLeftPane;
            newRow.ShowRightPane = tab.ShowRightPane;
            newRow.ShowOnMenu = tab.ShowOnMenu;

            // All users.
            newRow.AuthorizedRoles = tab.AuthorizedRoles;

           
            // Add the new TabRow to the Tab table
            ds.Tab.AddTabRow(newRow);

            // Save the changes 
            SaveSiteSettings();
            return newRow.ID;
        }


        //*********************************************************************
        //
        // UpdateTab Method <a name="UpdateTab"></a>
        //
        // The UpdateTab method updates the settings for the specified tab. 
        // These settings are stored in the Xml file PortalCfg.xml.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public void UpdateTab(Guid portalID, Guid tabID, Guid parentTabID, string tabName, int tabOrder, string authorizedRoles, string themeName, bool showLeftPane, bool showRightPane, bool showOnMenu, string staticUrl)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate tab in the Tab table and set the properties
            PortalDataSet.TabRow tabRow = ds.Tab.FindByID(tabID);
            tabRow.PortalID = portalID;
            tabRow.ParentID = parentTabID;
            tabRow.Name = tabName;
            tabRow.SortOrder = tabOrder;
            tabRow.AuthorizedRoles = authorizedRoles;
            tabRow.ThemeName = themeName;
            tabRow.ShowLeftPane = showLeftPane;
            tabRow.ShowRightPane = showRightPane;
            tabRow.ShowOnMenu = showOnMenu;
            tabRow.StaticUrl = staticUrl;

            // Save the changes 
            SaveSiteSettings();
        }

        //*********************************************************************
        //
        // UpdateTabOrder Method <a name="UpdateTabOrder"></a>
        //
        // The UpdateTabOrder method changes the position of the tab with respect
        // to other tabs in the portal.  These settings are stored in the Xml 
        // file PortalCfg.xml.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public void UpdateTabOrder(Guid tabID, int tabOrder)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate tab in the Tab table and set the property
            PortalDataSet.TabRow tabRow = ds.Tab.FindByID(tabID);

            tabRow.SortOrder = tabOrder;

            // Save the changes 
            SaveSiteSettings();
        }

        public void SwapTabSortOrder(Tab t1, Tab t2)
        {
            if (t1.SortOrder == t2.SortOrder)
            {
                t2.SortOrder = t1.SortOrder + 1;
            }

            int tmp = t1.SortOrder;
            t1.SortOrder = t2.SortOrder;
            t2.SortOrder = tmp;

            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate tab in the Tab table and set the property
            PortalDataSet.TabRow tabRow1 = ds.Tab.FindByID(t1.ID);
            tabRow1.SortOrder = t1.SortOrder;
            PortalDataSet.TabRow tabRow2 = ds.Tab.FindByID(t2.ID);
            tabRow2.SortOrder = t2.SortOrder;
            
            // Save the changes.
            SaveSiteSettings();
        }

        public void SwapModuleSortOrder(Module m1, Module m2)
        {
            int tmp = m1.SortOrder;
            m1.SortOrder = m2.SortOrder;
            m2.SortOrder = tmp;

            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate tab in the Tab table and set the property
            PortalDataSet.ModuleRow moduleRow1 = ds.Module.FindByID(m1.ID);
            moduleRow1.SortOrder = m1.SortOrder;
            PortalDataSet.ModuleRow moduleRow2 = ds.Module.FindByID(m2.ID);
            moduleRow2.SortOrder = m2.SortOrder;

            // Save the changes.
            SaveSiteSettings();
        }

        //-----------------------------------------------------------------------------------------
        public void DeleteTab(Guid tabID)
        {
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            //
            // Delete information in the Database relating to each Module being deleted
            //

            ds.Tab.RemoveTabRow(ds.Tab.FindByID(tabID));
            SaveSiteSettings();
        }

        //-----------------------------------------------------------------------------------------
        public void UpdateModuleSortOrder(Guid moduleID, int moduleSortOrder, string paneName)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table and update the properties
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            moduleRow.SortOrder = moduleSortOrder;
            moduleRow.PaneName = paneName;

            // Save the changes 
            SaveSiteSettings();
        }


        //-----------------------------------------------------------------------------------------
        public Guid AddModule(Guid tabID, int moduleSortOrder, string paneName, bool showEveryWhere, string title, Guid moduleDefinitionId, int cacheTime, string viewRoles, string addRoles, string editRoles, string deleteRoles, string approveRoles, string settingRoles, string managerRoles, string securityRoles)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Create a new ModuleRow from the Module table
            PortalDataSet.ModuleRow newModule = ds.Module.NewModuleRow();

            // Set the properties on the new Module
            newModule.ID = Guid.NewGuid();
            newModule.ModuleDefinitionID = moduleDefinitionId;
            newModule.SortOrder = moduleSortOrder;
            newModule.ShowEveryWhere = showEveryWhere;
            newModule.Title = title;
            newModule.PaneName = paneName;

            newModule.AuthorizedViewRoles = viewRoles;
            newModule.AuthorizedAddRoles = addRoles;
            newModule.AuthorizedEditRoles = editRoles;
            newModule.AuthorizedDeleteRoles = deleteRoles;
            newModule.AuthorizedApproveRoles = approveRoles;
            newModule.AuthorizedConfigureRoles = settingRoles;
            newModule.AuthorizedManageRoles = managerRoles;
            newModule.AuthorizedSecureRoles = securityRoles;

            newModule.CacheTimeout = cacheTime;
            newModule.TabRow = ds.Tab.FindByID(tabID);

            // Add the new ModuleRow to the Module table
            ds.Module.AddModuleRow(newModule);

            // Save the changes
            SaveSiteSettings();

            // Return the new Module ID
            return newModule.ID;
        }


        //-----------------------------------------------------------------------------------------
        public void UpdateModule(Guid moduleID, int moduleSortOrder, string paneName, bool showEveryWhere, string title, int cacheTime, string viewRoles, string addRoles, string editRoles, string deleteRoles, string approveRoles, string settingRoles, string managerRoles, string securityRoles)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table and update the properties
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            moduleRow.SortOrder = moduleSortOrder;
            moduleRow.ShowEveryWhere = showEveryWhere;
            moduleRow.Title = title;
            moduleRow.PaneName = paneName;
            moduleRow.CacheTimeout = cacheTime;

            moduleRow.AuthorizedViewRoles = viewRoles;
            moduleRow.AuthorizedAddRoles = addRoles;
            moduleRow.AuthorizedEditRoles = editRoles;
            moduleRow.AuthorizedDeleteRoles = deleteRoles;
            moduleRow.AuthorizedApproveRoles = approveRoles;
            moduleRow.AuthorizedConfigureRoles = settingRoles;
            moduleRow.AuthorizedManageRoles = managerRoles;
            moduleRow.AuthorizedSecureRoles = securityRoles;

            // Save the changes 
            SaveSiteSettings();
        }

        public void UpdateModule(Guid moduleId, string viewRoles, string addRoles, string editRoles, string deleteRoles, string approveRoles, string settingRoles, string managerRoles, string securityRoles)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table and update the properties
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleId);

            moduleRow.AuthorizedViewRoles = viewRoles;
            moduleRow.AuthorizedAddRoles = addRoles;
            moduleRow.AuthorizedEditRoles = editRoles;
            moduleRow.AuthorizedDeleteRoles = deleteRoles;
            moduleRow.AuthorizedApproveRoles = approveRoles;
            moduleRow.AuthorizedConfigureRoles = settingRoles;
            moduleRow.AuthorizedManageRoles = managerRoles;
            moduleRow.AuthorizedSecureRoles = securityRoles;

            // Save the changes 
            SaveSiteSettings();
        }

        public void UpdateModule(Guid moduleId, int moduleSortOrder, string paneName, bool showEveryWhere, string title, int cacheTime)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table and update the properties
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleId);

            moduleRow.SortOrder = moduleSortOrder;
            moduleRow.ShowEveryWhere = showEveryWhere;
            moduleRow.Title = title;
            moduleRow.PaneName = paneName;
            moduleRow.CacheTimeout = cacheTime;

            // Save the changes 
            SaveSiteSettings();
        }

        //-----------------------------------------------------------------------------------------
        public void DeleteModule(Guid moduleID)
        {
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            //
            // Delete information in the Database relating to Module being deleted
            //            

            ds.Module.RemoveModuleRow(ds.Module.FindByID(moduleID));
            SaveSiteSettings();
        }



        public static void UpdateModuleSettings(Guid moduleID, ModuleSettingItem[] settingItems)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();
            // if (ds == null) HttpContext.Current.Items["PortalDataSet"] = GetPortalDataSet();
            // Find the appropriate Module in the Module table
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            PortalDataSet.ModuleSettingRow[] settingRows = moduleRow.GetModuleSettingRows();
            PortalDataSet.ModuleSettingRow settingRow;
            foreach (ModuleSettingItem item in settingItems)
            {
                if (settingRows.Length == 0)
                {
                    // If there are no Setting elements at all, add one with the new name and value,
                    // but only if the value is not empty
                    if (item.Value != string.Empty)
                    {
                        settingRow = ds.ModuleSetting.NewModuleSettingRow();
                        settingRow.ModuleID = moduleRow.ID;
                        settingRow.Key = item.EditControl.ID;
                        settingRow.Value = item.Value;

                        ds.ModuleSetting.AddModuleSettingRow(settingRow);
                    }
                }
                else
                {
                    // Update existing setting element if it matches
                    bool found = false;
                    int i;

                    // Find which row matches the input parameter "key" and update the
                    // value.  If the value is string.Empty, however, delete the row.
                    for (i = 0; i < settingRows.Length; i++)
                    {
                        if (settingRows[i].Key == item.EditControl.ID)
                        {
                            if (item.Value == string.Empty)
                            {
                                // Delete the row
                                ds.ModuleSetting.RemoveModuleSettingRow(settingRows[i]);
                            }
                            else
                            {
                                // Update the value
                                settingRows[i].Value = item.Value;
                            }

                            found = true;
                            break;
                        }
                    }

                    if (found == false)
                    {
                        // Setting elements exist, however, there is no matching Setting element.
                        // Add one with new name and value, but only if the value is not empty
                        if (item.Value != string.Empty)
                        {
                            settingRow = ds.ModuleSetting.NewModuleSettingRow();
                            settingRow.ModuleID = moduleRow.ID;
                            settingRow.Key = item.EditControl.ID;
                            settingRow.Value = item.Value;

                            ds.ModuleSetting.AddModuleSettingRow(settingRow);
                        }
                    }
                }                
            }
            
            

            // Save the changes.
            SaveSiteSettings();            
        }

        //*********************************************************************
        //
        // UpdateModuleSetting Method  <a name="UpdateModuleSetting"></a>
        //
        // The UpdateModuleSetting Method updates a single module setting 
        // in the configuration file.  If the value passed in is string.Empty,
        // the Setting element is deleted if it exists.  If not, either a 
        // matching Setting element is updated, or a new Setting element is 
        // created.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public static void UpdateModuleSetting(Guid moduleID, object key, string value)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();
            // if (ds == null) HttpContext.Current.Items["PortalDataSet"] = GetPortalDataSet();
            // Find the appropriate Module in the Module table
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            PortalDataSet.ModuleSettingRow[] settingRows = moduleRow.GetModuleSettingRows();
            PortalDataSet.ModuleSettingRow settingRow;
            if (settingRows.Length == 0)
            {
                // If there are no Setting elements at all, add one with the new name and value,
                // but only if the value is not empty
                if (value != string.Empty)
                {
                    settingRow = ds.ModuleSetting.NewModuleSettingRow();
                    settingRow.ModuleID = moduleRow.ID;
                    settingRow.Key = key.ToString();
                    settingRow.Value = value;                    

                    ds.ModuleSetting.AddModuleSettingRow(settingRow);
                }
            }
            else
            {
                // Update existing setting element if it matches
                bool found = false;
                int i;

                // Find which row matches the input parameter "key" and update the
                // value.  If the value is string.Empty, however, delete the row.
                for (i = 0; i < settingRows.Length; i++)
                {
                    if (settingRows[i].Key == key.ToString())
                    {
                        if (value == string.Empty)
                        {
                            // Delete the row
                            ds.ModuleSetting.RemoveModuleSettingRow(settingRows[i]);
                        }
                        else
                        {
                            // Update the value
                            settingRows[i].Value = value;
                        }

                        found = true;
                        break;
                    }
                }

                if (found == false)
                {
                    // Setting elements exist, however, there is no matching Setting element.
                    // Add one with new name and value, but only if the value is not empty
                    if (value != string.Empty)
                    {
                        settingRow = ds.ModuleSetting.NewModuleSettingRow();
                        settingRow.ModuleID = moduleRow.ID;
                        settingRow.Key = key.ToString();
                        settingRow.Value = value;

                        ds.ModuleSetting.AddModuleSettingRow(settingRow);
                    }
                }
            }

            // Save the changes.
            SaveSiteSettings();
        }

        //*********************************************************************
        //
        // GetModuleSettings Method  <a name="GetModuleSettings"></a>
        //
        // The GetModuleSettings Method returns a hashtable of custom,
        // module-specific settings from the configuration file.  This method is
        // used by some user control modules (Xml, Image, etc) to access misc
        // settings.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        

        
        public static Hashtable GetModuleSettings(Guid moduleID)
        {
            // Create a new Hashtable
            Hashtable _settingsHT = new Hashtable();

            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            foreach (PortalDataSet.ModuleSettingRow sRow in moduleRow.GetModuleSettingRows())
            {
                _settingsHT[sRow.Key] = sRow.Value;
            }

            return _settingsHT;
        }


        public static Hashtable GetModuleSettings(Guid moduleID, PortalModuleControl control)
        {
            Hashtable setting = GetModuleSettings(moduleID, control.BaseSettings);
            return setting;
        }

        public static Hashtable GetModuleSettings(Guid moduleID, System.Web.UI.Page page)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            PortalDataSet.ModuleDefinitionRow moduledefineRow = ds.ModuleDefinition.FindByID(moduleRow.ModuleDefinitionID);

            PortalModuleControl portalModule = (PortalModuleControl)page.LoadControl(moduledefineRow.SourceFile);
            Hashtable setting = GetModuleSettings(moduleID, portalModule.BaseSettings);
            return setting;
        }


        public static Hashtable GetModuleSettings(Guid moduleID, Hashtable baseSettings)
        {
            // Create a new Hashtable
            Hashtable _settings = new Hashtable();

            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table
            PortalDataSet.ModuleRow moduleRow = ds.Module.FindByID(moduleID);

            foreach (PortalDataSet.ModuleSettingRow sRow in moduleRow.GetModuleSettingRows())
            {
                _settings[sRow.Key] = sRow.Value;
            }

            foreach (string key in baseSettings.Keys)
            {
                if (_settings[key] != null)
                {
                    ModuleSettingItem s = ((ModuleSettingItem)baseSettings[key]);
                    if (_settings[key].ToString() != string.Empty)
                        s.Value = _settings[key].ToString();
                }
            }
            return baseSettings;
        }


        //
        // MODULE DEFINITIONS
        //

        public DataRow[] GetModuleDefinitions(Guid portalID)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table
            return ds.ModuleDefinition.Select("1 = 1", "Name ASC");
        }

        public void AddModuleDefinition(Guid portalID, Guid moduleDefinitionID, string name, string sourceFile)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Create new ModuleDefinitionRow
            PortalDataSet.ModuleDefinitionRow newModuleDefinitionRow = ds.ModuleDefinition.NewModuleDefinitionRow();

            // Set the parameter values
            newModuleDefinitionRow.ID = moduleDefinitionID;
            newModuleDefinitionRow.Name = name;
            newModuleDefinitionRow.SourceFile = sourceFile;
            

            // Add the new ModuleDefinitionRow to the ModuleDefinition table
            ds.ModuleDefinition.AddModuleDefinitionRow(newModuleDefinitionRow);

            // Save the changes
            SaveSiteSettings();
        }

        //*********************************************************************
        //
        // DeleteModuleDefinition() Method <a name="DeleteModuleDefinition"></a>
        //
        // The DeleteModuleDefinition method deletes the specified module type 
        // definition from the portal.  Each module which is related to the
        // ModuleDefinition is deleted from each tab in the configuration
        // file, and all data relating to each module is deleted from the
        // database.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //    + <a href="DeleteModule.htm" style="color:green">DeleteModule Stored Procedure</a>
        //
        //*********************************************************************
        public void DeleteModuleDefinition(Guid definitionModuleID)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            //
            // Delete information in the Database relating to each Module being deleted
            //

            // Finish removing Module Definition
            ds.ModuleDefinition.RemoveModuleDefinitionRow(ds.ModuleDefinition.FindByID(definitionModuleID));

            // Save the changes 
            SaveSiteSettings();
        }

        //*********************************************************************
        //
        // UpdateModuleDefinition() Method <a name="UpdateModuleDefinition"></a>
        //
        // The UpdateModuleDefinition method updates the settings for the 
        // specified module type definition.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public void UpdateModuleDefinition(Guid moduleDefinitionID, string name, string sourceFile)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table and update the properties
            PortalDataSet.ModuleDefinitionRow moduleDefinitionRow = ds.ModuleDefinition.FindByID(moduleDefinitionID);
            moduleDefinitionRow.ID = moduleDefinitionID;
            moduleDefinitionRow.Name = name;
            moduleDefinitionRow.SourceFile = sourceFile;

            // Save the changes 
            SaveSiteSettings();
        }

        //*********************************************************************
        //
        // GetSingleModuleDefinition Method
        //
        // The GetSingleModuleDefinition method returns a ModuleDefinitionRow
        // object containing details about a specific module definition in the
        // configuration file.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public PortalDataSet.ModuleDefinitionRow GetSingleModuleDefinition(Guid definitionModuleID)
        {
            // Obtain SiteSettings from Current Context
            PortalDataSet ds = PortalConfiguration.GetPortalDataSet();

            // Find the appropriate Module in the Module table
            return ds.ModuleDefinition.FindByID(definitionModuleID);
        }

        private static string GetConfigFile()
        {
            string configFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["configFile"]);
            DomainsSection domainsSection = (DomainsSection)ConfigurationManager.GetSection("domains");
            DomainCollection domainCollection = domainsSection.Domains;
            foreach (DomainElement domain in domainCollection)
            {
                string name = domain.DomainName;
                string url = domain.DomainUrl;
                if (HttpContext.Current.Request.Url.AbsoluteUri.IndexOf(url) > -1)
                {
                    configFile = HttpContext.Current.Server.MapPath(string.Format("~/App_Data/{0}.xml", name));
                    break;
                }
            }
            
            return configFile;
        }

        private static string GetCurrentDomainName()
        {
            string domainName = "default";
            DomainsSection domainsSection = (DomainsSection)ConfigurationManager.GetSection("domains");
            DomainCollection domainCollection = domainsSection.Domains;
            foreach (DomainElement domain in domainCollection)
            {
                string name = domain.DomainName;
                string url = domain.DomainUrl;
                if (HttpContext.Current.Request.Url.AbsoluteUri.IndexOf(url) > -1)
                {
                    domainName = name;
                    break;
                }
            }
            
            return domainName;
        }

        //*********************************************************************
        //
        // GetSiteSettings Static Method
        //
        // The Configuration.GetSiteSettings Method returns a typed
        // dataset of the all of the site configuration settings from the
        // XML configuration file.  This method is used in Global.asax to
        // push the settings into the current HttpContext, so that all of the 
        // pages, content modules and classes throughout the rest of the request
        // may access them.
        //
        // The PortalDataSet object is cached using the ASP.NET Cache API,
        // with a file-change dependency on the XML configuration file.  Normallly,
        // this method just returns a copy of the object in the cache.  When the
        // configuration is updated and changes are saved to the the XML file,
        // the PortalDataSet object is evicted from the cache.  The next time 
        // this method runs, it will read from the XML file again and insert a
        // fresh copy of the PortalDataSet into the cache.
        //
        //*********************************************************************
        public static PortalDataSet GetPortalDataSet()
        {

            string configFile = GetConfigFile();
            string domainName = GetCurrentDomainName();
            PortalDataSet ds = (PortalDataSet) HttpContext.Current.Cache[domainName + "_PortalDataSet"];

            // If the PortalDataSet isn't cached, load it from the XML file and add it into the cache.
            if (ds == null)
            {
                // Create the dataset
                ds = new PortalDataSet();

                // Load the XML data into the DataSet
                ds.ReadXml(configFile);

                // Store the dataset in the cache
                HttpContext.Current.Cache.Insert(domainName + "_PortalDataSet", ds, new CacheDependency(configFile));
            }

            return ds;
        }

        //*********************************************************************
        //
        // SaveSiteSettings Method <a name="SaveSiteSettings"></a>
        //
        // The Configuration.SaveSiteSettings overwrites the the XML file with the
        // settings in the PortalDataSet object in context.  The object will in 
        // turn be evicted from the cache and be reloaded from the XML file the next
        // time GetSiteSettings() is called.
        //
        //*********************************************************************
        private static void SaveSiteSettings()
        {
            PortalDataSet ds = GetPortalDataSet();

            string configFile = GetConfigFile();
            ds.WriteXml(configFile);
        }
    }
}